package com.etc.service.impl;

import com.etc.dao.FlashGoodsStockDao;
import com.etc.dao.FlashOrderDao;
import com.etc.dao.UserAddressDao;
import com.etc.entity.FlashGoodsStock;
import com.etc.entity.FlashOrder;
import com.etc.entity.UserAddress;
import com.etc.entity.po.FlashOneLevelStatistics;
import com.etc.entity.po.FlashOrderMessage;
import com.etc.rabbitmq.FlashMessage;
import com.etc.redis.FlashGoodsKey;
import com.etc.redis.FlashSaleKey;
import com.etc.redis.RedisService;
import com.etc.service.FlashOrderService;
import com.etc.utils.PageData;
import com.etc.vo.OrderInfoMessage;
import com.etc.vo.UpdateFlashOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文件名:com.etc.service.impl
 * 描述：
 * 作者:吴仕泉
 * 时间:2019/5/27 17:43
 */
@Service
public class FlashOrderServiceImpl implements FlashOrderService {
    @Autowired
    UserAddressDao userAddressDao;

    @Autowired
    RedisService redisService;

    @Autowired
    FlashOrderDao flashOrderDao;

    @Autowired
    FlashGoodsStockDao flashGoodsStockDao;


    //下订单减库存
    @Transactional
    @Override
    public boolean PlaceAndOrder(FlashMessage fm) {
        //添加用户的收货地址
        UserAddress userAddress = new UserAddress();
        userAddress.setUserid(fm.getUserId());
        userAddress.setAddress(fm.getUserAddress());
        userAddress.setConsignee(fm.getUserName());
        userAddress.setConsigneetel(fm.getUserTel());
        int m = userAddressDao.inserteReturnPKey(userAddress);
        //获取秒杀订单编号
        String orderNum = getOrderNum("FO");
        //下订单
        FlashOrder fo = new FlashOrder();
        fo.setFlashordernum(orderNum);
        fo.setUserid(fm.getUserId());
        fo.setFlashsalary(fm.getFlashaslary());
        fo.setFlashordertime(new Date());
        fo.setFlashorderstatus(0);
        fo.setGoodsid(fm.getGoodsId());
        fo.setGoodsnum(fm.getGoodsNum());
        fo.setUseraddressid(userAddress.getAddressid());
        int i =  flashOrderDao.insertSelectiveRetrunId(fo);
        //减库存
        int n = flashGoodsStockDao.updateByFlashGoodsId(fm.getGoodsNum(),fm.getFlashGoodsId());
        if(i+n+m != 3){
            try {
                int error = 1 / 0;
            }catch (Exception e){
                System.out.println("下单失败");
            }finally {
                return false;
            }
        }else{
            redisService.set(FlashGoodsKey.getFlashGoodsOrder,fm.getUserId()+":"+fm.getFlashGoodsId(),fo);
            return true;
        }

    }


    //获得订单编号29190527181923000001OO 前12位是年月日时分秒，中间6位为订单在一分钟内的顺序，OO普通订单，FO秒杀订单
    public String getOrderNum(String type){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String datastr = sdf.format(new Date());
       // System.out.println("datastr"+datastr);
       Long num = redisService.get(FlashSaleKey.minuteOrderNum,"key",Long.class);
       if(num == null){
           redisService.set(FlashSaleKey.minuteOrderNum,"key",0);
       }
       num = redisService.incr(FlashSaleKey.minuteOrderNum,"key");
       String strNum = num.toString();
       int count =6- strNum.length();
       for(int i = 0 ;i<count;i++){
           strNum = "0"+strNum;
       }
       String orderNum = datastr+strNum+type;
        System.out.println("orderNum:"+orderNum);
        return orderNum;
    }

    //查询秒杀订单详情
    @Override
    public OrderInfoMessage findOrderInfo(String orderNum) {
        FlashOrderMessage fom = flashOrderDao.getOrderMessageByOrderNum(orderNum);
        if(fom == null){
            return null;
        }
        return  FlashOrderMessageRetrunOrderInfoMessage(fom);
    }

    //数据格式转化
    public OrderInfoMessage FlashOrderMessageRetrunOrderInfoMessage( FlashOrderMessage fom){
        OrderInfoMessage oim = new OrderInfoMessage();
        Date d = fom.getFlashordertime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String datastr = sdf.format(d);
        oim.setOrderdata(datastr);
        //订单信息
        oim.setFlashorderid(fom.getFlashorderid());
        oim.setOrderNum(fom.getFlashordernum());
        oim.setSureshopnum(fom.getGoodsnum());
        oim.setOrderstatus(fom.getFlashorderstatus());
        oim.setSurepice(fom.getFlashsalary());
        //收件人名字
        oim.setSureusername(fom.getConsignee());
        oim.setSureusertel(fom.getConsigneetel());
        oim.setAddress(fom.getAddress());
        //商品信息
        oim.setGoodid(fom.getGoodsid());
        oim.setGoodname(fom.getGoodsname());
        oim.setPriceurl(fom.getPictureurl());
        //商品分类
       // oim.setOnelevelid(fom.getOnelevelid());
        oim.setOnelevelname(fom.getOnelevelname());
        //oim.setTwolevelid(fom.getTwolevelid());
        oim.setTwolevelname(fom.getTwolevelname());
        return oim;
    }

    //查询所有订单以分页的形式进行展示
    @Override
    public PageData<OrderInfoMessage> findAllFlashOrderByPage(Integer page, Integer pageSize) {
        int star = (page -1)*pageSize;
        List<FlashOrderMessage> list =flashOrderDao.listAllOrderByPage(star,pageSize);
        List<OrderInfoMessage> oims = new ArrayList<>();
        for(int i = 0; i < list.size();i++){
            OrderInfoMessage oim = FlashOrderMessageRetrunOrderInfoMessage(list.get(i));
            oims.add(oim);
        }
        int count = flashOrderDao.getCount();
        PageData<OrderInfoMessage> pd = new PageData<>(oims,count,pageSize,page);
        pd.setCode(0);
        return pd;
    }

    //查询用户的所有秒杀订单
    @Override
    public List<OrderInfoMessage> findUserAllFlashInfo(Integer uid) {
        List<FlashOrderMessage> foms = flashOrderDao.listOrderMessageByUserId(uid);
        if(foms == null){
            return null;
        }
        List<OrderInfoMessage> oims = new ArrayList<>();
        for(int i = 0 ; i < foms.size();i++){
            oims.add(FlashOrderMessageRetrunOrderInfoMessage(foms.get(i)));
        }
        return oims;
    }

    //根据订单ID修改，订单的状态
    @Override
    public boolean updateOrderState(Integer foid, Integer state) {
        FlashOrder fo = new FlashOrder();
        fo.setFlashorderid(foid);
        fo.setFlashorderstatus(state);
        int num = flashOrderDao.updateByPrimaryKeySelective(fo);
        if(num > 0 ){
            return true;
        }
        return false;
    }

    //各大类本周销售情况
    @Override
    public List<FlashOneLevelStatistics> statisticsOneLevelData() {
        return flashOrderDao.listStatisticsOneLevelData();
    }

    //修改订单信息
    @Transactional
    @Override
    public boolean updateOrderMessage(UpdateFlashOrder ufo) {
        //获取订单信息
        FlashOrder fo = flashOrderDao.getFlashOrderByOrderNum(ufo.getOrdernum());

        UserAddress ua = new UserAddress(fo.getUseraddressid(),ufo.getUseraddress(),ufo.getUsername(),ufo.getUserphone());
        //修改地址
        int i = userAddressDao.updateByPrimaryKeySelective(ua);

        FlashOrder flashOrder = new FlashOrder();
        flashOrder.setFlashorderid(fo.getFlashorderid());
        flashOrder.setFlashorderstatus(Integer.parseInt(ufo.getFlashorderstatus()));
        int num = flashOrderDao.updateByPrimaryKeySelective(flashOrder);
        System.out.println("num:"+num);
        if((num+i) == 2){
            return true;
        }
        return false;
    }

    //总秒杀数量
    @Override
    public int selectFlashOrder() {
        return flashOrderDao.selectFlashOrder();
    }
    //这周的秒杀数量
    @Override
    public int selectDay() {
        return flashOrderDao.selectDay();
    }
}
